package com.atguigu.lease.admin.controller;

import com.atguigu.lease.admin.service.FeeKeyService;
import com.atguigu.lease.admin.service.FeeService;
import com.atguigu.lease.admin.service.FeeValueService;
import com.atguigu.lease.pojo.FeeKey;
import com.atguigu.lease.pojo.FeeValue;
import com.atguigu.lease.result.Result;
import com.atguigu.lease.vo.FeeVo;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RequestMapping("/admin/fee")
@RestController
public class FeeController {
    @Autowired
    private FeeService feeService;
    @Autowired
    private FeeKeyService feeKeyService;
    @Autowired
    private FeeValueService feeValueService;

    @GetMapping("/list")
    public Result<List<FeeVo>> listFee() {
        List<FeeVo> feeVoList =  feeService.listFee();
        return Result.success(feeVoList);
    }

    @PostMapping("/key/saveOrUpdate")
    public Result saveOrUpdateFeeKey(@RequestBody FeeKey feeKey) {
        feeKeyService.saveOrUpdate(feeKey);
        return Result.success(null);
    }

    @DeleteMapping("/key/deleteById")
    public Result deleteFeeKeyById(@RequestParam(value = "feeKeyId") Long id) {
        long count = feeValueService.count(Wrappers.lambdaQuery(FeeValue.class).eq(FeeValue::getFeeKeyId, id));
        if (count > 0){
            throw new RuntimeException("请先删除该费用项下的所有费用项值");
        }
        feeKeyService.removeById(id);
        return Result.success(null);
    }

    @PostMapping("/value/saveOrUpdate")
    public Result saveOrUpdateFeeValue(@RequestBody FeeValue feeValue) {
        feeValueService.saveOrUpdate(feeValue);
        return Result.success(null);
    }

    @DeleteMapping("/value/deleteById")
    public Result deleteFeeValueById(@RequestParam(value = "id") Long id) {
        feeValueService.removeById(id);
        return Result.success(null);
    }
}
